#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtCore, QtGui

class DcpuAsmHighlighter(QtGui.QSyntaxHighlighter):
    def __init__(self, parent):
        QtGui.QSyntaxHighlighter.__init__(self, parent)
        self.rules = []

        for keyword in ["pop", "push", "peek", "set", "add", "sub", "mul", "div", "mod", "shl",
                        "shr", "and", "bor", "xor", "ife", "ifn", "ifg", "ifb"]:
            rule = QtCore.QRegExp("(\\b|^)%s(\\b)" % keyword)
            rule.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
            format = QtGui.QTextCharFormat()
            format.setFontItalic(False)
            format.setFontWeight(QtGui.QFont.Bold)
            self.rules.append((rule, format))

        for register in ["a", "b", "c", "x", "y", "j", "i", "pc"]:
            rule = QtCore.QRegExp("(\\b|^)%s(\\b)" % register)
            rule.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
            format = QtGui.QTextCharFormat()
            format.setForeground(QtCore.Qt.darkBlue)
            format.setFontWeight(QtGui.QFont.Bold)
            self.rules.append((rule, format))

        rule = QtCore.QRegExp(";.*")
        format = QtGui.QTextCharFormat()
        format.setFontItalic(True)
        format.setForeground(QtCore.Qt.gray)
        self.rules.append((rule, format))

        rule = QtCore.QRegExp(":.*")
        format = QtGui.QTextCharFormat()
        format.setFontItalic(True)
        format.setForeground(QtCore.Qt.darkRed)
        self.rules.append((rule, format))


    def highlightBlock(self, text):
        for rule, format in self.rules:
            rule = QtCore.QRegExp(rule)
            rule.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
            index = rule.indexIn(text)
            print(index)
            while index >= 0:
                length = rule.matchedLength();
                self.setFormat(index, length, format)
                index = rule.indexIn(text, index + length)

class MainForm(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.layout = QtGui.QHBoxLayout(self)
        self.setWindowState(QtCore.Qt.WindowMaximized)
        self.text_edit = QtGui.QTextEdit()
        self.text_edit.setFontFamily("courier new")
        self.layout.addWidget(self.text_edit)
        self.highlighter = DcpuAsmHighlighter(self.text_edit)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    sys.exit(app.exec_())

